package com.itlong.cloud.app.service.impl;

import com.itlong.cloud.POJO.VO.app.robot.AppRobotLoginCacheVO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.app.service.IAppRobotLoginCacheService;
import com.itlong.cloud.constants.RedisConstant;
import com.itlong.cloud.service.RedisService;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.utils.encrypt.UserTokenUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

/**
 * <desc>
 *      机器人用户缓存信息业务处理接口实现类
 * </desc>
 *
 * @createDate 2018/10/15
 */
@Service
@RefreshScope
public class AppRobotLoginCacheServiceImpl implements IAppRobotLoginCacheService {

    @Autowired
    private RedisService<AppRobotLoginCacheVO> redisService;

    @Value("${" + PlatformConstants.APP_USER_TOKEN_KEY + "}")
    public String APP_USER_TOKEN_KEY;

    /**
     * <desc>
     *      获取机器人登录缓存
     * </desc>
     *
     * @param token 机器人登录token
     * @return 机器人登录缓存
     * @author wangzhi
     * @createDate 2018/10/15
     */
    @Override
    public AppRobotLoginCacheVO getRobotLoginCache(String token) {
        try {
            if (StringUtils.isBlank(token)) {
                return null;
            }
            //解密拿到userId
            String userId = UserTokenUtil.tokenDecrypt(token, APP_USER_TOKEN_KEY);
            if (userId == null) {
                return null;
            }
            AppRobotLoginCacheVO appRobotLoginCacheVO = redisService.getObject(RedisConstant.ROBOT_USER_REDIS_KEY + userId, AppRobotLoginCacheVO.class);
            if (appRobotLoginCacheVO != null && token.equals(appRobotLoginCacheVO.getToken())) {
                return appRobotLoginCacheVO;
            }
            return null;
        } catch (Exception e) {
            throw new DataAccessException("APP端【从缓存中获取机器人登录信息】获取失败") ;
        }
    }

}
